export class ConfigEncryptor {
    /**
     * 生成加密密钥
     * @param {string} password - 加密密码
     * @param {Uint8Array} [salt] - 可选盐值
     * @returns {Promise<CryptoKey>} - 加密密钥
     */
    static async generateKey(password, salt = crypto.getRandomValues(new Uint8Array(16))) {
        const keyMaterial = await crypto.subtle.importKey(
            "raw",
            new TextEncoder().encode(password),
            { name: "PBKDF2" },
            false,
            ["deriveKey"]
        );

        return {
            key: await crypto.subtle.deriveKey(
                {
                    name: "PBKDF2",
                    salt,
                    iterations: 100000,
                    hash: "SHA-256"
                },
                keyMaterial,
                { name: "AES-GCM", length: 256 },
                false,
                ["encrypt", "decrypt"]
            ),
            salt
        };
    }

    /**
     * 加密数据
     * @param {object} data - 要加密的数据
     * @param {string} password - 加密密码
     * @returns {Promise<{encrypted: number[], iv: number[], salt: number[]}>} - 加密后的数据
     */
    static async encrypt(data, password) {
        const { key, salt } = await this.generateKey(password);
        const iv = crypto.getRandomValues(new Uint8Array(12));
        const encrypted = await crypto.subtle.encrypt(
            { name: "AES-GCM", iv },
            key,
            new TextEncoder().encode(JSON.stringify(data))
        );

        return {
            encrypted: Array.from(new Uint8Array(encrypted)),
            iv: Array.from(iv),
            salt: Array.from(salt)
        };
    }

    /**
     * 解密数据
     * @param {{encrypted: number[], iv: number[], salt: number[]}} encryptedData - 加密数据
     * @param {string} password - 解密密码
     * @returns {Promise<object>} - 解密后的数据
     */
    static async decrypt(encryptedData, password) {
        const { key } = await this.generateKey(
            password,
            new Uint8Array(encryptedData.salt)
        );

        const decrypted = await crypto.subtle.decrypt(
            {
                name: "AES-GCM",
                iv: new Uint8Array(encryptedData.iv)
            },
            key,
            new Uint8Array(encryptedData.encrypted)
        );

        return JSON.parse(new TextDecoder().decode(decrypted));
    }
}